package com.lmy.springCloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 自定义Gateway过滤器
 */
@Component
@Slf4j
public class CustomGatewayFilter implements GlobalFilter, Ordered {
    /**
     * 核心方法，将过滤业务写在该方法中
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("CustomGatewayFilter被执行....");
        //获取到对应的参数和参数值
        ServerHttpRequest request = exchange.getRequest();
        //比如 http://localhost:20000/getMemberById/1?user=lmy&pwd=123456
        //获取请求参数中参数名为user的第一个值
        String user = request.getQueryParams().getFirst("user");
        //获取请求参数中参数名为pwd的第一个值
        String pwd = request.getQueryParams().getFirst("pwd");
        //如果不满足，就返回
        if (!("lmy".equals(user) && "123456".equals(pwd))) {
            log.info("--------非法用户---------");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        //如果满足，就放行
        return chain.filter(exchange);
    }

    /**
     * order表示过滤器执行的顺序，数字越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
